<template>
    <div class="sales-order-container">
        <!-- 页面头部 -->
        <div class="header">
            <h2>销货退货单<span v-if="code">编号:{{ code }}</span></h2>
            <div class="header-right">
                <el-button @click="onViewRecords">历史单据</el-button>
                <el-button type="primary" @click="saveAndNew" :disabled="isViewOnly">保存并新增</el-button>
                <el-button @click="save" :disabled="isViewOnly">保存</el-button>
                <el-button type="primary" @click="onSelectOrder" :disabled="isViewOnly">选择订单</el-button>
                <el-button @click="submit" :disabled="isViewOnly">提交</el-button>
                <el-button @click="audit" :disabled="isAudited">审核</el-button>
            </div>
        </div>

        <!-- 表单区域 -->
        <div style="background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
            <el-form :model="salesSlipForm" label-width="auto" inline :disabled="isViewOnly">
                <!-- 第一行表单 -->
                <div class="top-form">

                    <el-form-item label="客户：">
                        <el-input v-model="salesSlipForm.customerName" placeholder="点击选择客户" @click="openCustomerDialog"
                            readonly style="width: 200px;" />
                        <CustomerDialog v-model="customerDialogVisible" @confirm="handleSelectCustomer" />
                    </el-form-item>


                    <el-form-item label="销售员：" prop="workName">
                        <el-input v-model="salesSlipForm.workName" placeholder="业务员" style="width: 160px;" readonly />
                    </el-form-item>


                    <el-form-item label="单据日期：" prop="date">
                        <el-date-picker v-model="salesSlipForm.date" type="date" placeholder="选择日期"
                            style="width: 160px;" />
                    </el-form-item>
                    <!-- 

                    <el-form-item label="交货日期：" prop="returnDate">
                        <el-date-picker v-model="salesSlipForm.returnDate" type="date" placeholder="选择日期"
                            style="width: 160px;" />
                    </el-form-item> -->


                    <el-form-item label="客户地址：" prop="customer_address">
                        <el-input v-model="salesSlipForm.customer_address" placeholder="请输入地址" clearable
                            style="width: 160px;" />
                    </el-form-item>
                </div>
                <div style="height: 50px;"></div>
                <!-- 商品表格 -->
                <el-table :data="orderDetails" border stripe ref="tableRef" show-summary :summary-method="getSummaries"
                    summary-row-class-name="summary-row">
                    <!-- 序号列 -->
                    <el-table-column label="序号" width="80" align="center">
                        <template #default="scope">
                            <div class="seq-cell" @mouseenter="hoverIndex = scope.$index" @mouseleave="hoverIndex = -1"
                                v-if="!isAudited">
                                <span v-show="hoverIndex !== scope.$index" class="seq-number">
                                    {{ scope.$index + 1 }}
                                </span>
                                <div v-show="hoverIndex === scope.$index" class="operation-area">
                                    <span v-if="!hasSelectedSourceOrder" class="operation-btn add"
                                        @click.stop="addRow(scope.$index)" title="在下方添加行">+</span>
                                    <span class="operation-btn delete" @click.stop="deleteRow(scope.row)" title="删除当前行"
                                        :class="{ disabled: orderDetails.length <= 1 }"
                                        :disabled="orderDetails.length <= 1">−</span>
                                </div>
                            </div>
                            <div v-else class="seq-cell">{{ scope.$index + 1 }}</div>
                        </template>
                    </el-table-column>


                    <!-- 商品列 -->
                    <el-table-column label="*商品" align="left" min-width="150">
                        <template #default="scope">
                            <div class="product-cell" @click="!isAudited && openGoodsDialog(scope.$index)"
                                :style="{ cursor: isAudited ? 'default' : 'pointer' }">
                                <el-tag v-if="scope.row.productInfo?.name" closable
                                    @close="!isAudited && clearProduct(scope.row)" type="info"
                                    :disable-transitions="isAudited">
                                    {{ scope.row.productInfo.name }}
                                </el-tag>
                                <span v-else class="placeholder-text">请点击选择商品</span>
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column label="商品编号" align="center" width="100">
                        <template #default="scope">
                            {{ scope.row.code || '' }}
                        </template>
                    </el-table-column>

                    <el-table-column label="商品图片" align="center" width="100">
                        <template #default="scope">
                            <el-image v-if="scope.row.productInfo?.imageUrl" :src="scope.row.productInfo.imageUrl"
                                style="width: 50px; height: 50px" fit="cover"
                                :preview-src-list="[scope.row.productInfo.imageUrl]" />
                        </template>
                    </el-table-column>
                    <!-- 
                    <el-table-column label="单位" align="center" width="80">
                        <template #default="scope">
                            {{ scope.row.productInfo?.moreUnit || '' }}
                        </template>
                    </el-table-column> -->


                    <el-table-column label="基本单位" align="center" width="100">
                        <template #default="scope">
                            {{ scope.row.productInfo?.unit || '' }}
                        </template>
                    </el-table-column>

                    <el-table-column label="规格" align="center" width="80">
                        <template #default="scope">
                            {{ scope.row.productInfo?.specification || '' }}
                        </template>
                    </el-table-column>

                    <el-table-column label="品牌" align="center" width="80">
                        <template #default="scope">
                            {{ scope.row.productInfo?.brand || '' }}
                        </template>
                    </el-table-column>

                    <el-table-column label="仓库" width="120" align="center">
                        <template #default="scope">
                            <el-input v-model="scope.row.warehouse" readonly placeholder="(所有)"
                                @click="openWarehouseDialog(scope.row)" />
                        </template>
                    </el-table-column>


                    <!-- 赠品列 -->
                    <el-table-column label="赠品" align="center" width="120">
                        <template #default="scope">
                            <el-checkbox v-model="scope.row.gift" @change="handleGiftChange(scope.row)"
                                :disabled="isAudited" />
                        </template>
                    </el-table-column>

                    <el-table-column label="销售单价" align="center" width="120">
                        <template #default="scope">
                            <el-input v-model.number="scope.row.price" type="number" min="0" step="0.01"
                                style="width: 100%;" @change="calculateDetailPrice(scope.row)"
                                :disabled="isAudited || scope.row.gift" />
                        </template>
                    </el-table-column>

                    <el-table-column label="折扣率(%)" align="center" width="100">
                        <template #default="scope">
                            <el-input v-model.number="scope.row.discount" type="number" min="0" max="100" step="0.01"
                                style="width: 100%;" @change="calculateDetailPrice(scope.row)"
                                :disabled="isAudited || scope.row.gift" />
                        </template>
                    </el-table-column>
                    <el-table-column label="折扣额" align="center" width="100" prop="discountAmount">
                        <template #default="scope">
                            <el-input v-model.number="scope.row.discountAmount" disabled style="width: 100%;" />
                        </template>
                    </el-table-column>

                    <el-table-column label="折扣单价" align="center" width="120">
                        <template #default="scope">
                            <el-input v-model.number="scope.row.discountPrice" type="number" step="0.01"
                                style="width: 100%;" disabled />
                        </template>
                    </el-table-column>
                    <el-table-column label="金额" align="center" width="100" prop="cost">
                        <template #default="scope">
                            <el-input v-model.number="scope.row.cost" disabled style="width: 100%;" />
                        </template>
                    </el-table-column>
                    <el-table-column label="税率(%)" align="center" width="100">
                        <template #default="scope">
                            <el-input v-model.number="scope.row.tax" type="number" min="0" max="100" step="0.01"
                                style="width: 100%;" @change="calculateDetailPrice(scope.row)"
                                :disabled="isAudited || scope.row.gift" />
                        </template>
                    </el-table-column>

                    <el-table-column label="税额" align="center" width="100" prop="taxAmount">
                        <template #default="scope">
                            <el-input v-model.number="scope.row.taxAmount" disabled style="width: 100%;" />
                        </template>
                    </el-table-column>

                    <el-table-column label="税后单价" align="center" width="120">
                        <template #default="scope">
                            <el-input v-model.number="scope.row.taxPrice" type="number" step="0.01" style="width: 100%;"
                                disabled />
                        </template>
                    </el-table-column>

                    <el-table-column label="可退货数量" align="center" width="120" v-if="salesSlipForm.showReturnInfo">
                        <template #default="scope">
                            <span>{{ scope.row.useReturnCount }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="退货数量" align="center" width="100" prop="return_count">
                        <template #default="scope">
                            <el-input v-model.number="scope.row.return_count" type="number" min="1" step="1"
                                style="width: 100%;" @change="() => validateReturnQty(scope.row)"
                                :disabled="isAudited" />
                        </template>
                    </el-table-column>

                    <el-table-column label="价税合计" align="center" width="120" prop="totalPrice">
                        <template #default="scope">
                            <el-input v-model.number="scope.row.totalPrice" type="number" step="0.01"
                                style="width: 100%;" disabled />
                        </template>
                    </el-table-column>


                    <el-table-column prop="remarks" label="备注" min-width="150" show-overflow-tooltip>
                        <template #default="scope">
                            <el-input v-model="scope.row.remarks" placeholder="请输入备注" :disabled="isAudited"
                                style="width: 100%;" />
                        </template>
                    </el-table-column>
                </el-table>

                <div style="height: 50px;"></div>

                <div class="top-form" style="margin-top: 20px;">
                    <!-- <el-form-item label="优惠金额">
                        <el-input v-model.number="salesSlipForm.taxCost" placeholder="0.00" style="width: 160px;"
                            @input="updateEndCost" />
                    </el-form-item>
                    <el-form-item label="优惠后金额">
                        <el-input v-model.number="salesSlipForm.endCost" placeholder="0.00" style="width: 160px;" />
                    </el-form-item> -->
                    <!-- <el-form-item label="本次收款">
                        <el-input v-model.number="salesSlipForm.thisPayment" placeholder="0" style="width: 160px;"
                            @input="updateEndCost" />
                    </el-form-item> -->
                    <el-form-item label="本次退款：">
                        <el-input v-model.number="salesSlipForm.thisPayment" placeholder="0" style="width: 160px;"
                            @input="updateEndCost" />
                    </el-form-item>
                    <el-form-item label="本次欠款：">
                        <el-input v-model.number="salesSlipForm.thisDebt" placeholder="0" style="width: 160px;"
                            disabled />
                    </el-form-item>

                    <el-form-item label="收款到期日：" prop="returnDate">
                        <el-date-picker v-model="salesSlipForm.returnDate" type="date" placeholder="选择日期"
                            style="width: 160px;" />
                    </el-form-item>

                    <el-form-item label="交货方式：" prop="delivery">
                        <el-select v-model="salesSlipForm.delivery" placeholder="请选择" style="width: 160px;">
                            <el-option value="1" label="快递物流" />
                            <el-option value="2" label="自配" />
                            <el-option value="3" label="其他" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="收款账户：" prop="account">
                        <el-select v-model="salesSlipForm.account" placeholder="请选择" style="width: 160px;" clearable
                            :disabled="isAudited">
                            <el-option v-for="account in accountList" :key="account.account_id"
                                :label="account.account_code + account.account_name" :value="account.account_name" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="收款条件：" prop="payment">
                        <el-select v-model="salesSlipForm.payment" placeholder="请选择" style="width: 160px;" clearable>
                            <el-option value="1" label="现结" />
                            <el-option value="2" label="货到付款" />
                            <el-option value="3" label="分期付款" />
                            <el-option value="4" label="先款后付" />
                            <el-option value="5" label="月结" />
                            <el-option value="6" label="不定期付款" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="备注" prop="remarks">
                        <el-input v-model="salesSlipForm.remarks" type="textarea" :rows="3" placeholder="请输入备注信息"
                            style="width: 1050px;" />

                    </el-form-item>
                </div>
            </el-form>
        </div>

        <!-- 商品选择弹窗 -->
        <el-dialog v-model="goodsVisible" title="商品搜索列表" width="60%" style="height: auto;" draggable :show-close="true">
            <!-- 调用商品的搜索组件 -->
            <FreeGoodsSelect v-model="goodsVisible" @confirm="onGoodsSelected" />
        </el-dialog>
        <el-dialog v-model="salesSlipSelectVisible" title="选择源单（销售单）" width="90%" height="70vh" draggable>
            <SalesRecord :selectable="true" :pre-filter-customer-id="salesSlipForm.customerId"
                @select="handleSelectSalesSlip" />
        </el-dialog>
        <el-dialog v-model="warehouseVisible" title="仓库搜索列表" width="40%" style="height: auto;" draggable
            :show-close="true">
            <!-- 调用仓库的搜索组件 -->
            <WareHouse ref="warehouseRef"
                :info="{ selection: true, no: false, name: true, code: true, status: false, op: false, outButton: true }" />
            <br /><br />
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="warehouseVisible = false">取消</el-button>
                    <el-button type="primary" @click="warehouseVisible = false">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import CustomerDialog from '@/util/CustomerDialog.vue'
import FreeGoodsSelect from '@/util/FreeGoodsSelect.vue'
import SalesRecord from '@/views/sales/SalesRecord.vue'
import WareHouse from '@/views/basic/WareHouse.vue'



const router = useRouter()
const route = useRoute()


const staffName = sessionStorage.getItem('name')

const isEdit = ref(false)

// 是否为查看模式
const isViewOnly = computed(() => {
    const from = route.query.from
    return from === 'view' || isAudited.value
})
const salesSlipId = computed(() => route.query.id)
// const isEditable = computed(() => !isViewOnly.value)

const code = ref('')
const goodsVisible = ref(false)
const hoverIndex = ref(-1)
const isAudited = ref(false)

const openGoodsDialog = (index) => {
    currentIndex.value = index
    goodsVisible.value = true
}

let currentRow = ref(null), currentIndex = ref(null);
//仓库搜索选中结果
let warehouseVisible = ref(false)
let warehouseRef = ref();
watch(warehouseVisible, (newVisible) => {
    if (!newVisible) {
        if (warehouseRef.value && warehouseRef.value.selectedArray.length > 0) { //这里需要加上if判断，子组件中没有选择数据时为undefined，可能用于点击仓库，但是没选择，所以导致undefined报错
            currentRow.value.warehouse = warehouseRef.value.selectedArray[0].name //只选择一个，默认第一个
            //   currentRow.value.warehouseCode = warehouseRef.value.selectedArray[0].code //只选择一个，默认第一个
            //获取到仓库编码，存数据库用，仓库name仅用作展示
            //用完之后清空，避免污染其他地方数据
            warehouseRef.value.clearSelected();
        }
    }
})
function openWarehouseDialog(row) {
    warehouseVisible.value = true,
        currentRow.value = row;
}
// 表单数据
const salesSlipForm = reactive({
    salesOrderId: '',
    code: '',
    customer_code: '',
    workNumber: '',
    workName: staffName,
    date: new Date(),
    returnDate: '',
    customer_address: '',
    customerName: '',
    customerType: '',
    customerId: '',
    account: '',
    remarks: '',
    payment: '',
    delivery: '',
    // taxCost: 0,
    // endCost: 0,
    thisPayment: 0,
    thisDebt: 0,
    order_type: 1,
    showReturnInfo: false // 是否显示退货信息
})


// 销售单选择弹窗相关
const salesSlipSelectVisible = ref(false)
// 打开销售单选择对话框
const onSelectOrder = () => {
    if (!salesSlipForm.customer_code) {
        ElMessage.warning('请先选择客户')
        return
    }
    salesSlipSelectVisible.value = true
}

// 处理选择销售单源单
const handleSelectSalesSlip = async (selectedSlip) => {
    console.log('选中的销售单:', selectedSlip)

    const res = await axios.get('/api/sales/selectSalesSlip', {
        params: { id: selectedSlip.id }
    })

    if (res.data.code != 200) {
        ElMessage.error('加载销售单明细失败: ' + (res.data.msg || ''))
        return
    }

    const slip = res.data.salesSlip
    salesSlipForm.code = slip.code || ''
    salesSlipForm.salesOrderId = slip.id || ''
    const details = res.data.salesSlipDetList || []
    if (details.length == 0) {
        ElMessage.warning('该销售单无商品明细')
        return
    }

    const mappedRows = details.map(item => ({
        id: Date.now() + Math.random(),
        code: item.goods_code || item.code || '',
        productId: item.goodsId || '',
        productInfo: item.name ? {
            goodsId: item.goodsId,
            name: item.name,
            code: item.goods_code || item.code || '',
            specification: item.specification || '',
            brand: item.brand || '',
            unit: item.unit || '',
            moreUnit: item.moreUnit || '',
            price: item.price || 0,
            imageUrl: item.imageUrl || item.photo || '',
            warehouse: item.warehouse,
        } : null,
        warehouse: item.warehouse,
        useCount: item.useCount || 0,
        price: item.price || 0,
        discount: item.discount || 0,
        discountPrice: item.discountPrice || 0,
        tax: item.tax || 0,
        cost: item.cost || 0,
        useReturnCount: item.useReturnCount || 0,
        discountAmount: item.discountAmount || 0,
        taxAmount: item.taxAmount || 0,
        taxPrice: item.taxPrice || 0,
        quantity: item.quantity || 0,
        totalPrice: item.totalPrice || 0,
        remarks: item.remarks || '',
        gift: Boolean(item.gift)
    }))

    orderDetails.value = mappedRows
    salesSlipSelectVisible.value = false
    hasSelectedSourceOrder.value = true
    salesSlipForm.showReturnInfo = true
    ElMessage.success('已成功加载销售单商品明细')
}
// 退货数量校验
const validateReturnQty = (row) => {
    if (row.return_count > row.useReturnCount) {
        ElMessage.warning(`退货数量不能超过可退货数量 ${row.useReturnCount}`)
        row.return_count = row.useReturnCount
    }
    // 重新计算价格
    calculateDetailPrice(row)
}

// 是否已选择源单
const hasSelectedSourceOrder = ref(false)

// 商品明细（
const orderDetails = ref([
    {
        goodsId: '',
        code: '',
        productInfo: null,
        warehouse: '',
        useCount: 0,
        price: 0,
        discount: 0,
        discountPrice: 0,
        tax: 13,
        cost: 0,
        discountAmount: 0,
        taxAmount: 0,
        taxPrice: 0,
        return_count: 0,
        totalPrice: 0,
        remarks: '',
        gift: false
    }
])

// 商品选择
const onGoodsSelected = (selected) => {
    if (!selected || selected.length === 0) {
        goodsVisible.value = false
        return
    }
    
    const newRows = selected.map(item => ({
        code: item.code,
        goodsId: item.goodsIdd,
        productInfo: {
            goodsId: item.goodsId,
            name: item.name,
            code: item.code,
            specification: item.specification,
            brand: item.brandName,
            unit: item.unitName,
            moreUnit: item.unitName,
            price: item.price || 0,
            imageUrl: item.imageUrl || '',
            warehouse: item.warehouseName,
        },
        warehouse: item.warehouseName,
        useCount: item.availableStock || 0,
        price: item.price || 0,
        discount: 0,
        discountPrice: 0,
        tax: 0,
        taxAmount: 0,
        taxPrice: 0,
        return_count: 0,
        totalPrice: 0,
        remarks: '',
        gift: false
    }))


    const currentRow = orderDetails.value[currentIndex.value]
    if (currentRow && !currentRow.productInfo) {
        // 当前行是空的，直接替换为多行
        orderDetails.value.splice(currentIndex.value, 1, ...newRows)
    } else {
        // 当前行已有商品，或不确定，保险起见：在当前行下方插入
        orderDetails.value.splice(currentIndex.value + 1, 0, ...newRows)
    }

    // 重新计算价格
    newRows.forEach(row => {
        if (!row.gift) {
            calculateDetailPrice(row)
        }
    })

    goodsVisible.value = false
}
// // 处理赠品变化
// const handleGiftChange = (row) => {
//     if (row.gift) {
//         // 保存原始价格
//         row._originalPrice = {
//             price: row.price,
//             discount: row.discount,
//             tax: row.tax,
//             return_count: row.return_count
//         }
//         // 清零
//         row.price = 0
//         row.discount = 0
//         row.tax = 0
//         row.discountPrice = 0
//         row.taxAmount = 0
//         row.taxPrice = 0
//         row.totalPrice = 0
//     } else {
//         // 恢复
//         const original = row._originalPrice
//         row.price = original?.price ?? 0
//         row.discount = original?.discount ?? 0
//         row.tax = original?.tax ?? 0
//         row.return_count = original?.return_count
//         calculateDetailPrice(row)
//     }
//     updateEndCost()
// }
// 客户对话框启用
const customerDialogVisible = ref(false)
// 打开客户选择弹窗
const openCustomerDialog = () => {
    customerDialogVisible.value = true
}

// 客户选择
const handleSelectCustomer = (customers) => {
    console.log('已选择客户:', customers)
    if (customers && customers.length > 0) {
        // 修正了这里的变量名
        const customer = customers[0]
        salesSlipForm.customerId = customer.id
        salesSlipForm.customer_code = customer.code
        salesSlipForm.customer_address = customer.primaryContactAddress || ''
        salesSlipForm.customerName = customer.name
        salesSlipForm.customerType = customer.typeName

    }
    customerDialogVisible.value = false
}


// 验证订购数量
// const validateQuantity = (row) => {
//     if (row.return_count > row.useCount && row.useCount > 0) {
//         ElMessage.warning(`订购数量不能大于可用库存数量 ${row.useCount}`)
//         row.return_count = row.useCount
//         calculateDetailPrice(row)
//     }
// }

const calculateDetailPrice = (row) => {
    if (row.gift) {
        row.cost = 0
        row.discountAmount = 0
        row.discountPrice = 0
        row.taxPrice = 0
        row.totalPrice = 0
        row.taxAmount = 0
    } else {
        if (!row.productInfo || !row.price || !row.return_count || row.return_count < 1) {
            row.discountPrice = 0
            row.taxPrice = 0
            row.totalPrice = 0
            row.taxAmount = 0
            row.cost = 0
            row.discountAmount = 0
        } else {
            row.discountPrice = formatPrice(row.price * (1 - (row.discount || 0) / 100))
            row.taxPrice = formatPrice(row.discountPrice * (1 + (row.tax || 0) / 100))
            row.totalPrice = formatPrice(row.taxPrice * row.return_count)
            row.taxAmount = formatPrice((row.taxPrice - row.discountPrice) * row.return_count)
            row.discountAmount = formatPrice((row.price - row.discountPrice) * row.return_count)
            row.cost = formatPrice(row.discountPrice * row.return_count)
        }
    }
    updateEndCost()
}

const updateEndCost = () => {
    const total = orderDetails.value.reduce((sum, item) => sum + (item.totalPrice || 0), 0)
    const taxCost = parseFloat(salesSlipForm.taxCost) || 0
    salesSlipForm.endCost = parseFloat((total - taxCost).toFixed(2))
    salesSlipForm.thisDebt = parseFloat((salesSlipForm.endCost - salesSlipForm.thisPayment).toFixed(2))
}

//保留两位小数
const formatPrice = (num) => Math.round(num * 100) / 100
const getSummaries = ({ columns, data }) => {
    const sums = []
    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = '合计'
            return
        }
        if (column.property === 'return_count') {
            sums[index] = data.reduce((sum, row) => sum + (row.return_count || 0), 0)
            return
        }

        if (column.property === 'totalPrice') {
            sums[index] = formatPrice(data.reduce((sum, row) => sum + (row.totalPrice || 0), 0))

            return
        }
        if (column.property === 'taxAmount') {
            sums[index] = formatPrice(data.reduce((sum, row) => sum + (row.taxAmount || 0), 0))
            return
        }
        if (column.property === 'cost') {
            sums[index] = formatPrice(data.reduce((sum, row) => sum + (row.cost || 0), 0))
            return
        }

        if (column.property === 'discountAmount') {
            sums[index] = formatPrice(data.reduce((sum, row) => sum + (row.discountAmount || 0), 0))
            return
        }
        sums[index] = ''
    })
    return sums
}

const addRow = (index) => {
    orderDetails.value.splice(index + 1, 0, {
        goodsId: '',
        code: '',
        productInfo: null,
        warehouse: '',
        price: 0,
        discount: 0,
        discountPrice: 0,
        tax: 0,
        taxAmount: 0,
        taxPrice: 0,
        return_count: 0,
        totalPrice: 0,
        remarks: '',
        gift: false
    })
}

const deleteRow = (row) => {
    if (orderDetails.value.length <= 1) return
    const index = orderDetails.value.indexOf(row)
    orderDetails.value.splice(index, 1)
    updateEndCost()
}

// 格式化日期为 YYYY-MM-DD
const formatDate = (date) => {
    if (!date) return ''
    const d = new Date(date)
    const year = d.getFullYear()
    const month = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
}


// 回显销货单详情
const fetchSalesSlipDetail = async (paramsCode) => {
    try {
        const response = await axios.get('/api/sales/salesSlipByCode', {
            params: {
                returnCode: paramsCode,
                isReturn: 1
            }
        })

        if (response.data.code == 200) {
            console.log('回显数据:', response.data.salesSlip)
            const salesSlip = response.data.salesSlip
            const salesSlipDetList = response.data.salesSlipDetList || []

            // 回显主表数据
            salesSlipForm.id = salesSlip.id
            salesSlipForm.customer_code = salesSlip.customer_code || ''
            salesSlipForm.workNumber = salesSlip.workNumber || ''
            salesSlipForm.date = salesSlip.date ? new Date(salesSlip.date) : new Date()
            salesSlipForm.returnDate = salesSlip.returnDate ? new Date(salesSlip.returnDate) : ''
            salesSlipForm.customer_address = salesSlip.customer_address || ''
            salesSlipForm.remarks = salesSlip.remarks || ''
            salesSlipForm.payment = paymentLabelMap[salesSlip.payment] || salesSlip.payment
            salesSlipForm.delivery = deliveryLabelMap[salesSlip.delivery] || salesSlip.delivery
            salesSlipForm.thisPayment = salesSlip.thisPayment || 0
            salesSlipForm.thisDebt = salesSlip.thisDebt || 0
            salesSlipForm.order_type = salesSlip.orderType || 1
            code.value = salesSlip.returnCode || ''
            salesSlipForm.customerName = salesSlip.customerName
            salesSlipForm.account = salesSlip.account

            // 回显明细表数据
            orderDetails.value = salesSlipDetList.map(item => {
                const hasProduct = !!(item.goods_code || item.code);

                return {
                    code: item.goods_code || item.code || '',
                    goodsId: item.goodsId || '',
                    productInfo: hasProduct ? {
                        goodsId: item.goodsId,
                        name: item.name || '',
                        code: item.goods_code || item.code || '',
                        specification: item.specification || '',
                        brand: item.brand || '',
                        unit: item.unit || '',
                        moreUnit: item.moreUnit || '',
                        price: item.price || 0,
                        imageUrl: item.imageUrl || item.photo || item.image_url || ''
                    } : null,

                    warehouse: item.warehouse || '',
                    useCount: item.useCount || 0,
                    price: item.price || 0,
                    discount: item.discount || 0,
                    discountPrice: item.discountPrice || 0,
                    tax: item.tax || 0,
                    cost: item.cost || 0,
                    discountAmount: item.discountAmount || 0,
                    taxAmount: item.taxAmount || 0,
                    taxPrice: item.taxPrice || 0,
                    return_count: item.return_count || 0,
                    totalPrice: item.totalPrice || 0,
                    remarks: item.remarks || '',
                    gift: item.gift == 1 ? true : false
                };
            });

            if (orderDetails.value.length === 0) {
                addRow()
            }

            // 设置审核状态
            if (salesSlip.auditStatus === '2' || salesSlip.auditStatus === '3') {
                isAudited.value = true
            }
        } else {
            ElMessage.error('获取销货单详情失败: ' + (response.data.message || response.data.msg || '未知错误'))
        }
    } catch (error) {
        ElMessage.error('获取销货单详情失败: ' + error.message)
    }
}

// 清除商品
const clearProduct = (row) => {
    row.productInfo = null
    row.price = 0
    row.discountPrice = 0
    row.salesCost = 0
    row.discountAmount = 0
    row.taxAmount = 0
    row.taxPrice = 0
    row.totalPrice = 0
    row.return_count = 0
    row.tax = 13
    row.gift = false
    row.useCount = 0
    row.remarks = ''
    row.code = ''
    row.goodsId = ''
}
// 保存主逻辑
const save = async () => {

    if (!salesSlipForm.customer_code) {
        ElMessage.error('请选择客户')
        return false
    }

    const validDetails = orderDetails.value.filter(row => row.productInfo)
    if (validDetails.length === 0) {
        ElMessage.error('请至少选择一个商品')
        return false
    }

    for (const row of validDetails) {

        if (!row.return_count || row.return_count <= 0 || !Number.isInteger(row.return_count)) {
            ElMessage.error(`商品【${row.productInfo.name}】订购数量必须为正整数`)
            return false
        }
        if (!row.gift && (!row.price || row.price <= 0)) {
            ElMessage.error(`商品【${row.productInfo.name}】销售单价不能为空或小于等于0`)
            return false
        }
    }

    if (!salesSlipForm.date) {
        ElMessage.error('请选择单据日期')
        return false
    }

    //  确认
    try {
        await ElMessageBox.confirm('确定要保存此销货单吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
    } catch {
        return false
    }

    const salesSlip = {
        code: salesSlipForm.code,
        salesOrderId: salesSlipForm.salesOrderId,
        returnCode: code.value,
        customerId: salesSlipForm.customerId,
        customer_code: salesSlipForm.customer_code,
        customerType: salesSlipForm.customerType,
        customerName: salesSlipForm.customerName,
        workNumber: salesSlipForm.workNumber,
        workName: salesSlipForm.workName,
        date: formatDate(salesSlipForm.date),
        returnDate: formatDate(salesSlipForm.returnDate) || null,
        customer_address: salesSlipForm.customer_address,
        delivery: deliveryValueMap[salesSlipForm.delivery] || salesSlipForm.delivery,
        payment: paymentValueMap[salesSlipForm.payment] || salesSlipForm.payment,
        thisPayment: salesSlipForm.thisPayment,
        // taxCost: parseFloat(salesSlipForm.taxCost) || 0,
        // endCost: parseFloat(salesSlipForm.endCost) || 0,
        fristPayment: parseFloat(salesSlipForm.fristPayment) || 0,
        thisDebt: parseFloat(salesSlipForm.thisDebt) || 0,
        orderType: salesSlipForm.order_type,
        remarks: salesSlipForm.remarks,
        isReturn: 1,
        written_off_amount: salesSlipForm.thisPayment,
        notAmount: salesSlipForm.thisPayment,
        account: salesSlipForm.account,

        slipPrice: orderDetails.value.reduce((sum, row) => sum + (row.totalPrice || 0), 0),
        salesAmount: orderDetails.value.reduce((sum, row) => sum + (row.cost || 0), 0),
        itemCount: orderDetails.value.reduce((sum, row) => sum + (row.return_count || 0), 0),
        taxAmount: orderDetails.value.reduce((sum, row) => sum + (row.taxAmount || 0), 0),
    }

    const salesSlipDetList = validDetails.map(row => {
        const productInfo = row.productInfo || {};
        return {
            goodsId: row.goodsId,
            goods_code: row.code,
            warehouse: row.warehouse,
            price: parseFloat(row.price),
            discount: parseFloat(row.discount),
            tax: parseFloat(row.tax),
            return_count: row.return_count,
            gift: row.gift ? 1 : 0,
            brand: productInfo.brand,
            unit: productInfo.unit,
            moreUnit: productInfo.unitName || productInfo.moreUnit || productInfo.unit,
            specification: productInfo.specification,
            remarks: row.remarks,
            discountPrice: parseFloat(row.discountPrice),
            taxPrice: parseFloat(row.taxPrice),
            totalPrice: parseFloat(row.totalPrice),
            taxAmount: parseFloat(row.taxAmount),
            discountAmount: parseFloat(row.discountAmount),
            cost: parseFloat(row.cost),
            orderNumber: parseInt(row.useCount)
        }
    })



    if (code.value) {
        // 编辑模式
        const response = await axios.post('/api/sales/salesSlipUpdate', {
            salesSlip: {
                ...salesSlip,
                id: salesSlipId.value,
            },
            salesSlipDetList: salesSlipDetList
        })
        if (response.data.code == 200) {
            ElMessage.success('修改成功')
            return true
        } else {
            ElMessage.error('修改失败 : ' + response.data.msg)
            return false
        }
    } else {
        // 新增模式
        const response = await axios.post('/api/sales/salesSlipAdd', {
            salesSlip: salesSlip,
            salesSlipDetList: salesSlipDetList
        })
        if (response.data.code == 200) {
            code.value = response.data.salesSlipCode
            ElMessage.success('保存成功')
            return true
        } else {
            ElMessage.error('保存失败 : ' + response.data.msg)
            return false
        }
    }
}

// 保存并新增
const saveAndNew = async () => {
    const result = await save()
    if (result) {
        resetForm()
    }
}

const audit = () => {
    isAudited.value = true
    ElMessage.success('审核成功')
}

// 重置表单
const resetForm = () => {
    code.value = ''
    salesSlipForm.showReturnInfo = false
    salesSlipForm.customer_code = ''
    salesSlipForm.workNumber = ''
    salesSlipForm.date = new Date()
    salesSlipForm.returnDate = ''
    salesSlipForm.customer_address = ''
    salesSlipForm.remarks = ''
    salesSlipForm.payment = ''
    salesSlipForm.delivery = ''
    salesSlipForm.account = ''
    salesSlipForm.order_type = 1
    salesSlipForm.taxCost = 0
    salesSlipForm.endCost = 0
    salesSlipForm.fristPayment = 0
    salesSlipForm.thisPayment = 0
    salesSlipForm.thisDebt = 0
    orderDetails.value = [{
        goodsId: '',
        code: '',
        productInfo: null,
        warehouse: '',
        price: 0,
        discount: 0,
        discountPrice: 0,
        tax: 0,
        taxAmount: 0,
        taxPrice: 0,
        return_count: 0,
        totalPrice: 0,
        remarks: '',
        gift: false

    }]
    isAudited.value = false
}

const accountList =ref([])
const selectAccount = async () => {
    const response = await axios.get("/api/sales/selectAccountList")
    console.log('11', response.data)
    if (response.data.code == 200) {
        accountList.value = response.data.accountList  
        console.log('22', accountList.value)
    } else {
        ElMessage.error('获取账户列表失败 : ' + response.data.msg)
    }
}
const deliveryValueMap = {
    '快递物流': '1',
    '自配': '2',
    '其他': '3'
}

const paymentValueMap = {
    '现结': '1',
    '货到付款': '2',
    '分期付款': '3',
    '先款后付': '4',
    '月结': '5',
    '不定期付款': '6'
}

const deliveryLabelMap = {
    '1': '快递物流',
    '2': '自配',
    '3': '其他'
}

const paymentLabelMap = {
    '1': '现结',
    '2': '货到付款',
    '3': '分期付款',
    '4': '先款后付',
    '5': '月结',
    '6': '不定期付款'
}
//商品记录
const onViewRecords = () => {
    router.push({
        name: 'salesBackRecord',
    })
}

onMounted(() => {
    selectAccount()
    const id = route.query.id
    const paramsCode = route.query.code
    if (paramsCode) {
        salesSlipId.value = id
        isEdit.value = true
        fetchSalesSlipDetail(paramsCode)
    } else {
        resetForm()
    }

})
</script>

<style scoped>
/* 样式保持不变，可自行优化 */
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 10px;
    border-bottom: 1px solid #e4e7ed;
}

.header h2 {
    font-size: 1.5rem;
    color: #333;
    margin: 0;
}

.header-right {
    display: flex;
    gap: 8px;
    margin-left: auto;
}

.sales-order-container {
    padding: 20px;
    background-color: white;
    min-height: 85vh;
}

.top-form {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
    padding: 10px 0;
}

.seq-cell {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
}

.operation-area {
    display: flex;
    gap: 4px;
}

.operation-btn {
    cursor: pointer;
    font-weight: bold;
    width: 18px;
    text-align: center;
}

.operation-btn.add:hover {
    color: green;
}

.operation-btn.delete:hover:not(.disabled) {
    color: red;
}

.disabled {
    color: #ccc;
    pointer-events: none;
}

.product-cell {
    padding: 4px;
    min-height: 30px;
}

.placeholder-text {
    color: #999;
    font-size: 13px;
}

.summary-row {
    font-weight: bold;
}

/* 赠品列复选框居中 */
.el-table .cell .el-checkbox {
    display: flex;
    justify-content: center;
}
</style>